//
//  WishlistPersistentManager.m
//  iFoundIt
//
//  Created by Navid Shariat on 28/05/10.
//  Copyright 2010 QUT. All rights reserved.
//

#import "WishlistPersistentManager.h"


@implementation WishlistPersistentManager

@synthesize storeManager;

static sqlite3 *database = nil;
static NSString * dbname=@"ifoundit.sqlite";

- (void) dealloc{
	if (storeManager)
		[storeManager release];
	[super dealloc];
}

- (StorePersistentManager*) storeManager{
	if (!storeManager)
		storeManager=[[StorePersistentManager alloc] init];
	return storeManager;
}

#pragma mark CRUD
- (void) insertItem: (WishedItem*) wishedItem{
	NSString * dbPath=[self getDBPath];
	NSLog(dbPath);
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		sqlite3_stmt *addStmt;	
		const char *sql = "insert into WishList(searchKeyword, distance, longtitude, latitude) Values(?, ?, ? ,?)";
		if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));		
		int wishItemId=-1;
		sqlite3_bind_text(addStmt, 1, [[wishedItem searchKeyword] UTF8String], -1, SQLITE_TRANSIENT);
		sqlite3_bind_double(addStmt, 2, [wishedItem radius]);
		sqlite3_bind_double(addStmt, 3, [wishedItem fromLocationCoordinate].longitude);
		sqlite3_bind_double(addStmt, 4, [wishedItem fromLocationCoordinate].latitude);
	
		if(SQLITE_DONE != sqlite3_step(addStmt))
			NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
		else
			wishItemId = sqlite3_last_insert_rowid(database);
	
	//Reset the add statement.
		sqlite3_reset(addStmt);
	}
	
}
- (void) updateItem: (WishedItem*) wishedItem{
	NSString * dbPath=[self getDBPath];
	NSLog(dbPath);
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		sqlite3_stmt *updateStmt;	
		const char *sql = "UPDATE WishList SET SearchKeyword=?,  distance=?, longtitude=?, latitude=? WHERE itemID=?";
		if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));		
		
		sqlite3_bind_text(updateStmt, 1, [[wishedItem searchKeyword] UTF8String], -1, SQLITE_TRANSIENT);
		sqlite3_bind_double(updateStmt, 2, [wishedItem radius]);
		sqlite3_bind_double(updateStmt, 3, [wishedItem fromLocationCoordinate].longitude);
		sqlite3_bind_double(updateStmt, 4, [wishedItem fromLocationCoordinate].latitude);
		sqlite3_bind_int(updateStmt, 5, [wishedItem wishedItemID]);
		
		if(SQLITE_DONE != sqlite3_step(updateStmt))
			NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
		
		//Reset the add statement.
		sqlite3_reset(updateStmt);
	}
	
	
}
- (void) deleteItem: (WishedItem*) wishedItem{
	NSString * dbPath=[self getDBPath];
	NSLog(dbPath);
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		sqlite3_stmt *deleteStmt;	
		const char *sql = "DELETE FROM WishList WHERE itemID=?";
		if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));		
		sqlite3_bind_int(deleteStmt, 1, [wishedItem wishedItemID]);
		
		if(SQLITE_DONE != sqlite3_step(deleteStmt))
			NSAssert1(0, @"Error while deleting data. '%s'", sqlite3_errmsg(database));		
		//Reset the add statement.
		sqlite3_reset(deleteStmt);		
	}
}

- (NSMutableArray*) getWishlist{
	NSMutableArray* list=[[NSMutableArray alloc] init];
	NSString * dbPath=[self getDBPath];
	NSLog(dbPath);
	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		const char * sql = "SELECT * FROM WishList"; 
		sqlite3_stmt *selectstmt;
		int sqlResult=sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL);
		NSLog([NSString stringWithFormat:@"%i", sqlResult] );
		if(sqlResult == SQLITE_OK) {			
			while(sqlite3_step(selectstmt) == SQLITE_ROW) {				
				WishedItem * wishedItem=[[WishedItem alloc]init];
				[wishedItem setWishedItemID:sqlite3_column_int(selectstmt, 0)];
				[wishedItem setSearchKeyword: [NSString  stringWithUTF8String:sqlite3_column_text(selectstmt,1)]];
				[wishedItem setRadius:sqlite3_column_double(selectstmt, 2)];
				CLLocationCoordinate2D coordinate;
				coordinate.longitude=sqlite3_column_double(selectstmt, 3);
				coordinate.latitude=sqlite3_column_double(selectstmt, 4);
				[wishedItem setFromLocationCoordinate:coordinate];
				CLLocation * location= [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude: coordinate.longitude];
				BOOL exists= [[self storeManager] storeExists:[wishedItem searchKeyword] :location :([wishedItem radius]*1000)];
				[wishedItem setItemStatus:exists];
				[location release];
				[list addObject: wishedItem]; 
				[wishedItem release];
			}
		}
	}
	else
		sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
	return list;
}

#pragma mark methods

- (NSString *) getDBPath {	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent:dbname];	
}

@end
